﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Windows.Input;

namespace LegtionMVVM
{
    public class RelayCommand : ICommand
    {
        #region Fields
        
        private Action _execute;
        readonly Action<object> _executeWithParam;
        readonly Func<bool> _canExecute;
        private Func<object, bool> _canExecuteWithParam;

        #endregion 

        #region Constructors

        public RelayCommand(Action execute)
            : this(execute, null)
        {

        }

        /// <summary>
        /// Creates a new command that can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }
        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<object> execute, Func<bool> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _executeWithParam = execute;
            _canExecute = canExecute;
        }
        public RelayCommand(Action execute, Func<bool> canExecute)
        {            
            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion // Constructors

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute();
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                    FastSmartEventSource.Instance.Event += value;
            }
            remove
            {
                if (_canExecute != null)
                    FastSmartEventSource.Instance.Event -= value;
            }
        }

        public void Execute(object parameter)
        {
            _executeWithParam(parameter);
        }

        #endregion // ICommand Members     
    }
 
}
